package com.example.inventorywarningdemo.service.impl;

import com.example.inventorywarningdemo.Exception.EmailException;
import com.example.inventorywarningdemo.config.AlertConfig;
import com.example.inventorywarningdemo.dto.EmailDTO;
import com.example.inventorywarningdemo.service.EmailService;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {
    private final JavaMailSender mailSender;
    private final AlertConfig alertConfig;

    @Override
    public void sendAlertEmail(EmailDTO emailDTO) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            // 设置发件人
            helper.setFrom(alertConfig.getFromEmail());
            // 解析多个收件人
            String[] toEmails = emailDTO.getTo().split(",\\s*");
            helper.setTo(toEmails);
//            helper.setTo(emailDTO.getTo());
            // 设置主题和内容
            helper.setSubject(emailDTO.getSubject());
            helper.setText(emailDTO.getContent());

            // 抄送
            if (StringUtils.hasText(alertConfig.getCcEmails())) {
                helper.setCc(alertConfig.getCcEmails().split(",\\s*"));
            }
            // 密送
            if (StringUtils.hasText(alertConfig.getBccEmails())) {
                helper.setBcc(alertConfig.getBccEmails().split(",\\s*"));
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new EmailException("邮件发送失败", e);
        }
    }
}